package cn.ffcs.uec.staffAndOutStaff.component;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.web.servlet.Servlets;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Div;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import cn.ffcs.uec.staffAndOutStaff.component.bean.StaffAndOutStaffListboxExtBean;
import cn.ffcs.uec.staffAndOutStaff.manager.StaffAndOutStaffManager;
import cn.ffcs.uec.staffAndOutStaff.vo.StaffAndOutStaff;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.DateUtil;
import cn.ffcs.uom.common.util.ExportExcelNew;
import cn.ffcs.uom.common.util.IPortletInfoProvider;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.vo.PageInfo;
import lombok.Getter;
import lombok.Setter;

/**
 * 人员花名册
 * 
 * @Title:
 * @Description:
 * @author Wang Yiren
 * @版权 FFCS（C） 2017
 * @date 2018年9月12日
 */
@Controller
@Scope("prototype")
public class StaffAndOutStaffListboxExt extends Div implements IdSpace {

    private static final long serialVersionUID = 7004119232729703597L;

    private static final String STAFF_AND_OUTSTAFF_ZUL = "/pages_nmg/staffAndOutStaff/comp/staffAndOutStaff_listbox_ext.zul";

    private StaffAndOutStaffListboxExtBean bean = new StaffAndOutStaffListboxExtBean();

    private StaffAndOutStaff staffAndOutStaff = new StaffAndOutStaff();

    private StaffAndOutStaffManager staffAndOutStaffManager = (StaffAndOutStaffManager) ApplicationContextUtil
            .getBean("staffAndOutStaffManager");

    List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

    @Getter
    @Setter
    private IPortletInfoProvider portletInfoProvider;

    public StaffAndOutStaffListboxExt() {
        Executions.createComponents(STAFF_AND_OUTSTAFF_ZUL, this, null);
        Components.wireVariables(this, bean);
        Components.addForwards(this, this, '$');
        // 转发
        // this.addForward("onOrgTreeStaffAndOutStaffQuery", this,
        // "onOrgTreeStaffAndOutStaffQueryResponse");
        // onQuery();
    }

    /**
     * 界面初始化
     */
    public void onCreate() {
    }

    /**
     * 监听组织树抛出的事件
     * 
     * @param event
     */
    /*
     * public void onOrgTreeStaffAndOutStaffQueryResponse(final ForwardEvent
     * event) { staffAndOutStaff = (StaffAndOutStaff)
     * event.getOrigin().getData(); if (null != staffAndOutStaff) {
     * this.bean.getStaffCode().setValue(null);
     * this.bean.getStaffName().setValue(null);
     * staffAndOutStaff.setStaffName(null); staffAndOutStaff.setStaffCode(null);
     * } // 执行查询 onQuery(); }
     */
    /**
     * 双击选中事件
     */
    public void onStaffAndOutStaffSelectRequest() {
        if (this.bean.getStaffAndOutStaffListboxs().getSelectedCount() > 0) {
            staffAndOutStaff = (StaffAndOutStaff) this.bean.getStaffAndOutStaffListboxs().getSelectedItem().getValue();
            if (staffAndOutStaff != null) {
            }
        }
    }

    /**
     * 查询员工信息
     * 
     * @throws Exception
     *             异常
     */
    public void onQueryStaffAndOutStaff() {
        int activePage = bean.getStaffAndOutStaffListboxPaging().getActivePage();
        int pageSize = bean.getStaffAndOutStaffListboxPaging().getPageSize();
        PageInfo pageInfo = staffAndOutStaffManager.queryPageInfoByStaffAndOutStaff(staffAndOutStaff, activePage + 1,
                pageSize);
        // 清单下载数据
        data = staffAndOutStaffManager.getStaffAndOutStaffData(staffAndOutStaff);
        // 总条数
        if(pageInfo !=null) {
	        bean.getTotalSize().setValue(String.valueOf(pageInfo.getTotalCount()));
	        ListModel list = new BindingListModelList(pageInfo.getDataList(), true);
	        this.bean.getStaffAndOutStaffListboxs().setModel(list);
	        this.bean.getStaffAndOutStaffListboxPaging().setTotalSize(pageInfo.getTotalCount());
        }
    }

    /**
     * 每页显示事件
     */
    public void onPageSizeSelect() {
        if (this.bean.getPageListbox() != null && this.bean.getPageListbox().getSelectedItem().getValue() != null) {
            this.bean.getStaffAndOutStaffListboxPaging().setActivePage(0);
            this.bean.getStaffAndOutStaffListboxPaging()
                    .setPageSize(Integer.parseInt(this.bean.getPageListbox().getSelectedItem().getValue().toString()));
        }
        this.onQueryStaffAndOutStaff();
    }

    /**
     * 翻页
     */
    public void onStaffAndOutStaffListboxPaging() {
        onQueryStaffAndOutStaff();
    }

    /**
     * 报表参数赋值按钮
     * 
     * @throws Exception
     * @throws SuspendNotAllowedException
     */
    public void onReportParametr() throws SuspendNotAllowedException, Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("opType", "confirm");
        Window window = (Window) Executions.createComponents("/pages_nmg/advanceQuery/reportParameter_main.zul", null,
                map);
        window.doModal();
        window.addEventListener("onOK", new EventListener() {

            @Override
            public void onEvent(Event event) throws Exception {
                if (event.getData() != null) {
                    staffAndOutStaff = (StaffAndOutStaff) event.getData();
                    onQueryStaffAndOutStaff();
                }
            }
        });
    }

    /**
     * 清单下载按钮
     * 
     * @throws Exception
     */
    public void onDownloadlist() throws Exception {
        if (data !=null && data.size() != 0) {
            // 设置字符集
            String charset = "UTF-8";
            String fileName = "人员花名册_" + DateUtil.getYYYYMMDD(new Date());
            HttpServletRequest httpRequest = (HttpServletRequest) Executions.getCurrent().getNativeRequest();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ExportExcelNew.exportExcel("", data, os);
            byte[] content = os.toByteArray();
            String encodedName = null;
            encodedName = URLEncoder.encode(fileName + ".xlsx", charset);
            // 将空格替换为+号
            encodedName = encodedName.replace("%20", "+");
            // 解决ie6 bug 或者是火狐浏览器
            if (encodedName.length() > 150 || Servlets.isGecko(httpRequest) || Servlets.isGecko3(httpRequest)) {
                encodedName = new String(encodedName.getBytes(charset), "ISO8859-1");
            }
            Filedownload.save(content, "application/octet-stream", encodedName);
        } else {
            Messagebox.show("数据为空!");
            return;
        }
    }

    /**
     * 重置按钮
     */
    public void onReset() {
        clearVariable();
        this.bean.getTotalSize().setValue(null);
        /*
         * this.bean.getStaffName().setValue(null);
         * this.bean.getStaffCode().setValue(null);
         */
        ListboxUtils.clearListbox(this.bean.getStaffAndOutStaffListboxs());
        this.bean.getStaffAndOutStaffListboxPaging().setTotalSize(1);
        staffAndOutStaff = new StaffAndOutStaff();
    }

    /**
     * 清除变量
     */
    public void clearVariable() {
        staffAndOutStaff = null;
        data.clear();
    }
}
